<?php
namespace app\admin\controller;


use app\common\base\AuthenticatedController;
use app\common\base\Form;
use think\Db;


/**
 * 设备控制器
 * Class DeviceController
 * @package app\admin\controller
 */
class DeviceController extends AuthenticatedController {


    public function Add() {

        Form::Validate([
            'name'                  =>  'require',
            'device_classify_id'    =>  'require|integer',
            'image'                 =>  'require',
            'device_attr'           =>  'require',
        ]);

        $data = [
            'visible'               =>  true,
            'name'                  =>  input('name'),
            'image'                 =>  input('image'),
            'device_classify_id'    =>  input('device_classify_id'),
            'device_attr'           =>  input('device_attr'),
        ];

        $result = Db::table('device')->insert($data);
        if (!$result) {
            return Error('添加失败');
        }

        return Success('添加设备成功');

    }


    public function Delete() {

        Form::Validate([
            'id'  =>  'require',
        ]);

        if (!Db::table('device')->where('id', input('id'))->delete()) {
            return Error('删除失败');
        }

        return Success('删除成功');

    }


    public function Modify() {

        Form::Validate([
            'id'                    =>  'require|integer',
            'name'                  =>  'require',
            'device_classify_id'    =>  'require|integer',
            'image'                 =>  'require',
            'device_attr'           =>  'require',
        ]);

        $data = [
            'visible'               =>  true,
            'name'                  =>  input('name'),
            'image'                 =>  input('image'),
            'device_classify_id'    =>  input('device_classify_id'),
            'device_attr'           =>  input('device_attr'),
        ];

        if (Db::table('device')->where('id', input('id'))->update($data) === false) {
            return Error('更新失败');
        }

        return Success('更新成功');
    }


    public function GetList() {
        $classify = Db::table('device_classify')->select();

        foreach ($classify as $key => $value) {
            $list = Db::table('device')->where('device_classify_id', $value['id'])->select();
            $classify[$key]['device_list'] = $list;
        }

        return Success('获取成功', $classify);
    }


    public function GetOne() {
        Form::Validate([
            'id'    =>  'require|integer'
        ]);

        $result = Db::table('device')->where('id', input('id'))->find();
        if (!$result) {
            return Error('获取失败');
        }

        return Success('获取成功', $result);

    }

}